package study.sharding.spring.support.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import study.sharding.spring.support.routing.DataSourceKeyHolder;

@Slf4j
@Aspect
@Order(-1)// 保证该AOP在@Transactional之前执行
@Component
public class DataSourceAspect {

	@Before("@annotation(dataSource))")
	public void switchDataSource(JoinPoint point, TargetDataSource dataSource) {
		String value = dataSource.value();
		if (DataSourceKeyHolder.containKey(value)) {
			//切换数据源
			DataSourceKeyHolder.setKey(value);
			String s = point.getSignature().toShortString();
			log.info(">>>>>> Method [{}] Use DataSource [{}]", s, value);
		} else {
			log.warn(">>>>>> DataSource [{}] Error, Use Default DataSource", value);
		}
	}

	@After("@annotation(dataSource))")
	public void resetDataSource(JoinPoint point, TargetDataSource dataSource) {
		// 将数据源置为默认数据源
		DataSourceKeyHolder.clearKey();
		log.info("Reset DataSource to [" + DataSourceKeyHolder.getKey()+ "] in method [" + point.getSignature() + "]");
	}
}
